package client;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;


// test client
public class ClientMain {
 
    final static int buffsize = 1024;
    private static byte[] receivedBuffer = new byte[buffsize];
    private static byte[] sentBuffer;

    private static String sentFileName = "wifigeo_lib/sniff.xml";
    private static String serverAddress = "127.0.0.1" ;
    private static int serverPort = 5554 ;

    
    /**
     * Receive packet  
     * @param DatagramSocket socket
     * @param DatagramPacket packet
     * @return DatagramPacket packet
     */
    public static DatagramPacket receivepacket (DatagramSocket socket) {
        DatagramPacket packet = new DatagramPacket(receivedBuffer, buffsize);
    	try {
            socket.receive(packet);
            System.out.println( "Cs : Received " + packet.getLength() + " bytes from " + packet.getAddress() +" on port "+ socket.getLocalPort()+"  from port " + packet.getPort());
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Cannot listen the socket");
            System.exit(-4);
        }
		return packet;
    } 
    /**
     * Send packet  
     * @param DatagramSocket socket
     * @param DatagramPacket packet
     */
    public static void sendpacket (DatagramSocket socket, DatagramPacket packet) {
        try {
            System.out.println( "Cs : Sending " + packet.getLength() + " bytes on " + packet.getAddress()+" on port "+ socket.getLocalPort() +" to port " + packet.getPort());
            socket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Error in sending data");
        }
    }

    /**
     * Convert from File to byte
     * @param File file
     * @return byte[]
     */
    public static byte[] getBytesFromFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);
        long length = file.length();

        byte[] bytes = new byte[(int)length];
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
                && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead;
                }

        is.close();

        // Do something with the read bytes
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }
        return bytes;
    }

    public static byte[] loadFile(String pathname)  {
    	///////////////////////////////// GET POWER DATA XML 

        File fileXml = new File (pathname) ;
        byte[] buffer = new byte[(int) fileXml.length()] ;
        InputStream xmlFileStream = null ;

        try {
            //File input stream in InputStream
            xmlFileStream = new FileInputStream (fileXml);;
            /*
             * while( ( atom = xmlFileStream.read()) != -1)
             content.append((char)atom);
             */
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("C : File " + fileXml.getAbsolutePath() + " not found");
        }

        //Fill buffer with the file
        try {
            System.out.println("C : Will send " + xmlFileStream.available() + " bytes before blocking state in reading");
            xmlFileStream.read(buffer) ;

        } catch (IOException e) {
            e.printStackTrace();
        }
        //System.out.println("The file has " + getBytesFromFile(fileXml) + " bytes");
        System.out.println("C : The buffer to send has " + buffer.length + " bytes");
        
        // /!\ buffer.lengh = xmlFileStream.available()

        //	System.exit(-1);

        /*
           System.out.println("File contents :");
           System.out.println(content);
           */
    	return buffer;
    }

    public static DatagramSocket createSocket()  {

    	///////////////////////////////// CREATE THE SOCKET 
	    DatagramSocket seSocket = null;
	
	    try {
	        //client port
	        seSocket = new DatagramSocket();
	        seSocket.setSoTimeout(5000);
	    } catch (SocketException e) {
	        System.out.println("C : Could not create socket on local port !"+e);
	        System.exit(-1);
	    }
	
	    System.out.println("C : Send socket created");
	    
	    return seSocket; 
    }
	public static String getInput(){

	    Scanner in = new Scanner(System.in);
	    String choice = in.next();
	    return choice;
	}

	
    public static void main(String[] args) throws IOException  {
    
    	
    	//File sent by client
        System.out.println("<<<< Put the link of the xml file to send.\n Current \n" + sentFileName);
        String tmp = getInput();
        
        if ( new File(tmp).exists() ){
        	sentFileName = getInput() ;	
        	System.out.println("New file used" + sentFileName);
        }else
        	System.out.println("Old file used" + sentFileName);
	    
	    System.out.println("<<<< Put port number of the server. (Current " +serverPort+" )");
	    serverPort = Integer.parseInt(getInput()) ;
	    
	    System.out.println("<<<< Put server IP. (Current " +serverAddress+" )");
	    serverAddress = getInput() ;
	    
	    System.out.println("<<<< How many request ?");
	    int nbClient = Integer.parseInt(getInput()) ;
        //IP 
        //byte[] ip = new byte[4] {(byte)127,(byte)0,(byte)0,(byte)1}; // ipv4
        //byte[] ip = new byte[16]; // ipv6
        //InetAddress hostAddress = InetAddress.getByAdress(ip);
        //Get server InetAddress 
        InetAddress hostAddress =   InetAddress.getByName(serverAddress);// Oserver.getInetAddress();
        
        sentBuffer= loadFile(sentFileName) ;
     
        for (int i = 0; i < nbClient ; i++){
        	 TClient tclient = new TClient(hostAddress, serverPort, sentBuffer);

    		//Create new client thread
	    	Thread child = new Thread(tclient);
	    	//Launch the child
	    	child.start();
        }
     //   seSocket.close();
    }
}

